package com.zhaofei.webtong;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SplashActivity extends AppCompatActivity {
    private List<View> viewList;
    private ViewPager viewpager;
    private LinearLayout indicator;
    private Button mButton;
    private List<String> imgStrings = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        viewpager = findViewById(R.id.viewpager);
        indicator = findViewById(R.id.indicator);
        mButton = findViewById(R.id.enter);
        viewList = new ArrayList<>();

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
                finish();
            }
        });
        initData();
    }

    private void initData() {
        final RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest("http://sp.zgmycy.cn/api/api/getBootsImage", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (response.toString().length() > 0) {

                    Gson gson = new Gson();

                    imgStrings = gson.fromJson(response.toString(), new TypeToken<ArrayList<String>>() {
                    }.getType());
                    addImges(imgStrings);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        requestQueue.add(stringRequest);
    }

    private void addImges(List<String> imgStrings) {
        for (int i = 0; i < imgStrings.size(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.imageviews, null);

            ImageView imageView = (ImageView) view.findViewById(R.id.iv);

            Glide.with(this).load(imgStrings.get(i)).into(imageView);
            viewList.add(view);

        }
        addPots();
        setAdapters();
        setListener();
    }


    private int position = 0, oldPosition = 0;

    private void addPots() {
        for (int i = 0; i < imgStrings.size(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(R.drawable.cricle_gray);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(20, 0, 20, 0);
            imageView.setLayoutParams(params);

            indicator.addView(imageView);
        }
        indicator.getChildAt(position).setBackgroundResource(R.drawable.cricle_black);
        oldPosition = position;
    }

    private void setAdapters() {
        viewpager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return viewList.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewList.get(position));
                return viewList.get(position);
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setListener() {
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicator.getChildAt(oldPosition).setBackgroundResource(
                        R.drawable.cricle_gray);
                indicator.getChildAt(position)
                        .setBackgroundResource(R.drawable.cricle_black);
                oldPosition = position;
                if (position == imgStrings.size()-1){
                    mButton.setVisibility(View.VISIBLE);
                }else {
                    mButton.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewpager.setOnTouchListener(new View.OnTouchListener() {
            float startX;
            float startY;
            float endX;
            float endY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getX();
                        startY = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        endX = event.getX();
                        endY = event.getY();
                        WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
//获取屏幕的宽度
                        Point size = new Point();
                        windowManager.getDefaultDisplay().getSize(size);
                        int width = size.x;
//首先要确定的是，是否到了最后一页，然后判断是否向左滑动，并且滑动距离是否符合，我这里的判断距离是屏幕宽度的4分之一（这里可以适当控制）
                        if (oldPosition == (imgStrings.size() - 1) && startX - endX > 0 && startX - endX >= (width / 5)) {

                            startActivity(new Intent(getApplicationContext(), MainActivity.class));
                            finish();
                        }
                        break;
                }
                return false;
            }
        });

    }
}
